在學 React 的時候,你可能聽過一句話:
React component 應該要是 pure function。
但什麼是 pure function?為什麼它對 React 這麼重要?今天我們就從最基礎開始聊。
純函數有兩個關鍵特徵:
// 純函數
function add(a, b) {
return a + b;
}
// 不純函數:偷偷改了外部狀態
let counter = 0;
function addAndCount(a, b) {
counter++;
return a + b;
}
第一個函數完全可預測;第二個會隨著外部 counter
改變結果 → 不純。
可以把 React component 想像成數學公式:
UI = f(state, props)
props
和 state
相同時,component 的輸出(UI)也要相同。如果 component 是 pure:
👉 注意:pure component 並不會阻止 React 呼叫 render function(仍會 re-render),只是確保 Virtual DOM 沒變時,不會觸發 DOM 更新。若要連 re-render 本身也跳過,需要搭配 React.memo
。
如果 component 不純:
props
卻輸出不同 UI → React 無法正確優化。fetch
、使用 Math.random()
或 Date.now()
。Render 階段(必須保持 pure):
props
+ state
計算出 Virtual DOMEffect 階段(專門處理副作用):
在 render 之後,React 會執行 hooks:
useEffect
→ 處理非同步副作用(例如 API 請求、事件監聽)useLayoutEffect
→ 處理同步 DOM 操作(例如元素尺寸計算、樣式調整)👉 React 強制副作用只能放在這些 hooks,就是為了保持 render 階段的純度。這樣一來,相同的 props/state 就能保證輸出相同的 UI,避免不可預期的結果。
function Hello({ name }) {
return <h1>Hello {name}</h1>;
}
props.name
→ 永遠輸出一樣的 UI。let calls = 0;
function HelloCounter({ name }) {
calls++; // 修改外部變數
return <h1>Hello {name}, rendered {calls} times</h1>;
}
props.name
,輸出卻會改變。判斷以下 component 是否 pure:
function Greeting({ name }) {
let upper = name.toUpperCase();
return <h1>Hello {upper}</h1>;
}
👉 答案:Pure ✅
因為 upper
每次 render 都重新計算,只要 props.name
一樣 → 輸出也一樣。
英文
A pure function always returns the same output for the same input and has no side effects.
In React, this means that if a component’s props and state are the same, it should always render the same UI.
React enforces this by separating side effects into hooks like useEffect and useLayoutEffect, keeping the render phase pure and predictable.
中文
純函數的定義是:相同輸入 → 相同輸出,且沒有副作用。
在 React 中,這代表當 component 的 props 和 state 相同時,輸出的 UI 應該相同。
為了維持這種純度,React 規範副作用必須放在 useEffect
或 useLayoutEffect
,避免污染 render,讓 component 可預測、可優化。
UI = f(state, props)
。useEffect
/ useLayoutEffect
,render 階段保持純淨。